package com.wanyu.video.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        // 使用谷歌浏览器访问，会发现每次请求，都会有两个，最后一个请求msg类型为EmptyLastHttpContent类型，
        if(msg instanceof HttpRequest){
            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.uri());
            if(uri.getPath().equals("/favicon")){
                System.out.println("请求了 favicon, 不做响应");
                return;
            }

        }
        System.out.println("msg 类型 " + msg.getClass());
        System.out.println("客户端地址 ： " + ctx.channel().remoteAddress());
            // 回复信息给浏览器
        ByteBuf content = Unpooled.copiedBuffer("客户端回复：hello im server", CharsetUtil.UTF_8);
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; Charset=UTF-8").set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
        ctx.writeAndFlush(response);
    }
}
